package com.recipedb.sprint.repository;

import com.recipedb.sprint.entity.KeywordCount;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Repository
public interface KeywordCountRepository extends JpaRepository<KeywordCount, Long> {

    @Query("select k from KeywordCount k order by k.totalCount desc")
    List<KeywordCount> findTopKeywords(PageRequest pageable);

    default List<KeywordCount> findTopKeywords(int limit) {
        return findTopKeywords(PageRequest.of(0, limit));
    }

    @Modifying
    @Transactional
    @Query(value = """
            insert into keyword_count (keyword, total_count)
            values (:keyword, 1)
            on conflict (keyword)
            do update set total_count = keyword_count.total_count + 1
            """, nativeQuery = true)
    void upsertKeyword(String keyword);
}
